package top.lyc829.mymusic.interceptor

import android.Manifest
import android.app.Activity
import android.content.Context
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.lzx.starrysky.SongInfo
import com.lzx.starrysky.intercept.AsyncInterceptor
import com.lzx.starrysky.intercept.InterceptorCallback
import com.lzx.starrysky.utils.showToast
import top.lyc829.mymusic.MyApp


/**
 * @Author lyc
 * @create 2021-07-04 21:08
 */
class PermissionInterceptor constructor(private val mContext: Context) : AsyncInterceptor() {
    override fun process(songInfo: SongInfo?, callback: InterceptorCallback) {
        if (songInfo == null) {
            callback.onInterrupt(RuntimeException("SongInfo is null"))
            return
        }
        XXPermissions.with(mContext)
            .permission(Permission.RECORD_AUDIO)
            .permission(Permission.READ_EXTERNAL_STORAGE)
            .permission(Permission.WRITE_EXTERNAL_STORAGE)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: List<String>, all: Boolean) {
                    if (all) {
                        callback.onContinue(songInfo)
                    } else {
                        callback.onInterrupt(RuntimeException("没有权限，播放失败"))
                        mContext.showToast("没有权限，播放失败")
                    }
                }

                override fun onDenied(permissions: List<String>, never: Boolean) {
                    if (never) {
                        callback.onInterrupt(RuntimeException("没有权限，播放失败"))
                        mContext.showToast("没有权限，播放失败")
                    } else {
                        callback.onInterrupt(RuntimeException("没有权限，播放失败"))
                        mContext.showToast("没有权限，播放失败")
                    }
                }
            })
    }

    override fun getTag(): String = "PermissionInterceptor"
}